package com.example.nick.bodyapplication.xml

import android.content.Context
import org.w3c.dom.Document
import org.w3c.dom.Element
import org.w3c.dom.Node
import org.w3c.dom.NodeList
import javax.xml.parsers.DocumentBuilder
import javax.xml.parsers.DocumentBuilderFactory

class DomHelper {
    companion object {
        fun queryXml(ctx: Context): ArrayList<Person> {
            val Persons = ArrayList<Person>()
            try {
                //①获得DOM解析器的工厂示例:
                val dbFactory = DocumentBuilderFactory.newInstance()
                //②从Dom工厂中获得dom解析器
                val dbBuilder: DocumentBuilder = dbFactory.newDocumentBuilder()
                //③把要解析的xml文件读入Dom解析器
                val doc: Document = dbBuilder.parse(ctx.assets.open("person2.xml"))
                println("处理该文档的DomImplemention对象=" + doc.implementation)
                //④得到文档中名称为person的元素的结点列表
                val nList: NodeList = doc.getElementsByTagName("person")
                //⑤遍历该集合,显示集合中的元素以及子元素的名字
                for (i in 0 until nList.length) {
                    //先从Person元素开始解析
                    val personElement = nList.item(i) as Element
                    val p = Person()
                    p.id = Integer.valueOf(personElement.getAttribute("id"))

                    //获取person下的name和age的Note集合
                    val childNoList: NodeList = personElement.childNodes
                    for (j in 0 until childNoList.length) {
                        val childNode: Node = childNoList.item(j)
                        //判断子note类型是否为元素Note
                        if (childNode.nodeType === Node.ELEMENT_NODE) {
                            val childElement = childNode as Element
                            if ("name" == childElement.nodeName) {
                                p.name = childElement.firstChild.nodeValue
                            } else if ("age" == childElement.nodeName) {
                                p.age = Integer.valueOf(childElement.firstChild.nodeValue)
                            }
                        }
                    }
                    Persons.add(p)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
            return Persons
        }
    }
}